﻿using B.S.NewMedical.Api.Write.Application.Command.Order.Refund;
using B.S.NewMedical.Domain.Order;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.Order.Refund
{
    /// <summary>
    /// 删除退款处理器
    /// </summary>
    public class DeleteRefundCommandHandle : IRequestHandler<DeleteRefundCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RefundModel> _refundRepository;
        private readonly ILogger<DeleteRefundCommandHandle> _logger;

        public DeleteRefundCommandHandle(
            IBaseRepository<RefundModel> refundRepository,
            ILogger<DeleteRefundCommandHandle> logger)
        {
            _refundRepository = refundRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(DeleteRefundCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                _logger.LogInformation("开始删除退款记录，ID：{Id}", request.Id);

                // 1. 查找要删除的退款记录
                var refund = _refundRepository.GetAll()
                    .FirstOrDefault(x => x.Id == request.Id && !x.IsDeleted);

                if (refund == null)
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "未找到要删除的退款记录";
                    _logger.LogWarning("未找到要删除的退款记录，ID：{Id}", request.Id);
                    return result;
                }

                // 2. 检查退款记录状态，防止删除已完成的退款
                if (!string.IsNullOrEmpty(refund.Status) && 
                    refund.Status.Equals("已完成", StringComparison.OrdinalIgnoreCase))
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "已完成的退款记录不能删除";
                    _logger.LogWarning("尝试删除已完成的退款记录，ID：{Id}，状态：{Status}", 
                        request.Id, refund.Status);
                    return result;
                }

                // 3. 检查退款记录状态，防止删除已处理的退款
                if (!string.IsNullOrEmpty(refund.Status) && 
                    refund.Status.Equals("已处理", StringComparison.OrdinalIgnoreCase))
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "已处理的退款记录不能删除";
                    _logger.LogWarning("尝试删除已处理的退款记录，ID：{Id}，状态：{Status}", 
                        request.Id, refund.Status);
                    return result;
                }

                // 4. 检查退款记录状态，防止删除已审核的退款
                if (!string.IsNullOrEmpty(refund.Status) && 
                    refund.Status.Equals("已审核", StringComparison.OrdinalIgnoreCase))
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "已审核的退款记录不能删除";
                    _logger.LogWarning("尝试删除已审核的退款记录，ID：{Id}，状态：{Status}", 
                        request.Id, refund.Status);
                    return result;
                }

                // 5. 执行逻辑删除
                refund.IsDeleted = true;
                refund.UpdateTime = DateTime.Now;

                // 6. 更新数据库
                var updateResult = await _refundRepository.UpdateAsync(refund);

                if (updateResult > 0)
                {
                    result.Code = ApiEnum.Success;
                    result.Msg = "退款记录删除成功";
                    result.Data = updateResult;
                    
                    _logger.LogInformation("退款记录删除成功，ID：{Id}，服务编号：{ServiceId}，用户：{UserName}，退款金额：{RefundAmount}，状态：{Status}", 
                        refund.Id, refund.ServiceId, refund.UserName, refund.Refund, refund.Status);
                }
                else
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "退款记录删除失败";
                    result.Data = updateResult;
                    
                    _logger.LogError("退款记录删除失败，ID：{Id}", request.Id);
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Error;
                result.Msg = $"删除退款记录时发生异常：{ex.Message}";
                
                _logger.LogError(ex, "删除退款记录时发生异常，ID：{Id}，异常信息：{Message}", 
                    request.Id, ex.Message);
            }

            return result;
        }
    }
}
